package cn.cocho.android.mc.file;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import cn.cocho.android.mc.log.LoggerUtils;

/**
 * 操作Properties文件
 * 
 * @author HAIKANG SONG
 * @time 2013-4-19下午3:11:29
 */
public class PropertiesUtils {

	/**
	 * 获取资源文件
	 * 
	 * @param proPath
	 *            资源文件路径
	 * @return
	 * @author HAIKANG SONG
	 * @time 2013-4-19下午2:18:34
	 */
	public static Properties getProperties(String proPath) {
		Properties prop = null;
		InputStream in = null;
		try {
			in = new FileInputStream(proPath);
			if (in != null) {
				prop = new Properties();
				prop.load(in);
			}
		} catch (IOException e) {
			LoggerUtils.error(PropertiesUtils.class.getName(), "读取资源文件（" + proPath + "）时出错！", e);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
			}
		}
		return prop;
	}

	/**
	 * 根据资源文件路径和键获得值
	 * 
	 * @param proPath
	 *            资源文件路径
	 * @param key
	 *            键
	 * @return
	 * @author HAIKANG SONG
	 * @time 2013-4-19下午2:40:03
	 */
	public static Object getValue(String proPath, String key) {
		Properties pro = getProperties(proPath);
		return pro.get(key);
	}

	/**
	 * 将键值对信息保存到指定的资源文件
	 *
	 * @param proPath 资源文件路径
	 * @param key 键
	 * @param value 值
	 * @return 
	 * @author HAIKANG SONG
	 * @time 2013-4-19下午3:09:13
	 */
	public static boolean put(String proPath, String key, String value) {
		boolean result =false;
		Properties pro = new Properties();
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(proPath);
			pro.load(in);// 从输入流中读取属性列表（键和元素对）
			out = new FileOutputStream(proPath);
			pro.setProperty(key, value);
			pro.store(out, "Update '" + key + "' value");
			result =true;
		} catch (IOException e) {
			LoggerUtils.error(PropertiesUtils.class.getName(), "将键为[" + key + "]，值为[" + value + "]的信息，写入文件[" + proPath + "]中出错！", e);
		} finally {
			try {
				in.close();
				out.flush();
				out.close();
			} catch (IOException e) {
			}
		}
		return result;
	}

	/**
	 * 将资源信息保存到指定的资源文件中，应结合getProperties使用
	 *
	 * @param proPath 资源文件路径
	 * @param pro 资源信息
	 * @return 
	 * @author HAIKANG SONG
	 * @time 2013-4-19下午3:09:47
	 */
	public static boolean save(String proPath, Properties pro) {
		boolean result = false;
		OutputStream out = null;
		try {
			out = new FileOutputStream(proPath);
			pro.store(out, "save");
			result = true;
		} catch (FileNotFoundException e) {
			LoggerUtils.error(PropertiesUtils.class.getName(), "将信息写入文件[" + proPath + "]中出错！", e);
		} catch (IOException e) {
			LoggerUtils.error(PropertiesUtils.class.getName(), "将信息写入文件[" + proPath + "]中出错！", e);
		} finally {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
			}
		}
		return result;
	}

}
